package com.zmh.arithmetic.linked_list;

import java.util.List;

/**
 * 链表反转
 *
 * @author zmh
 * @create 2018-11-20 上午10:40
 **/
public class ReverseLinkedList {
    static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) { val = x; }
    }

    public ListNode reverseListByRecursion(ListNode head) {
        if (null == head || null == head.next) {
            return head;
        }
        ListNode newHead = reverseListByRecursion(head.next);
        head.next.next = head;
        //处理最后情况
        head.next = null;

        return newHead;
    }

    public ListNode reserverListByLoop(ListNode head) {
        ListNode previous = null;
        ListNode current = head;
        while (null != current) {
            ListNode temp = current.next;
            current.next = previous;
            previous = current;
            current = temp;
        }

        return previous;
    }

    public static void main(String[] args) {
        ListNode listNode = new ListNode(1);
        ListNode listNode2 = new ListNode(2);
        ListNode listNode3 = new ListNode(3);
        ListNode listNode4 = new ListNode(4);
        ListNode listNode5 = new ListNode(5);
        listNode.next = listNode2;
        listNode2.next = listNode3;
        listNode3.next = listNode4;
        listNode4.next = listNode5;
        ReverseLinkedList reverseLinkedList = new ReverseLinkedList();
        ListNode reverseList = reverseLinkedList.reverseListByRecursion(listNode);
        while (reverseList != null) {
            System.out.println(reverseList.val);
            reverseList = reverseList.next;
        }
    }
}
